﻿using System;
using System.Collections.Generic;
using System.Web;
using He.Web.UI;
using System.Text;
using He.Common;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using He.API.Translate.Bing;

namespace He.Web.Tools
{
    /// <summary>
    /// data_copy 的摘要说明
    /// </summary>
    public class data_copy : AjaxHandler
    {
        UI.Manage bk = new UI.Manage();
        Upload upload = new Upload();
        public string threadKey;
        public override void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (!bk.IsAdminLogin())
            {
                EchoJson(0, "您还未登陆，请先登陆");
                return;
            }
            //设置缓存键存储当前进程
            threadKey = InputUtil.Get("threadKey");
            CacheHelper.Add(threadKey, "拷贝开始<br />");
            string action = InputUtil.Get("act");
            switch (action)
            {
                case "copy_category":
                    copy_category(context);
                    break;
                case "copy_channel":
                    copy_channel(context);
                    break;
            }
        }

        #region 批量拷贝分类下数据===================================
        private void copy_category(HttpContext context)
        {
            bool copy_all = InputUtil.Get("copy_all") == "1" ? true : false;
            bool translate = InputUtil.Get("is_translate") == "1" ? true : false;
            bool clear_tags = InputUtil.Get("clear_tags") == "1" ? true : false;
            bool make_thumb = InputUtil.Get("make_thumb") == "1" ? true : false;
            int img_width = InputUtil.Get("img_width", 0);

            int from_category_id = InputUtil.Get("fromCategoryId", 0);
            int to_category_id = InputUtil.Get("toCategoryId", 0);

            string id_list = InputUtil.Form("idlist");

            //获取相对应的类别信息
            BLL.category cbll = new BLL.category();
            Model.category from_cmodel = cbll.GetModel(from_category_id);
            Model.category to_cmodel = cbll.GetModel(to_category_id);

            //获取相对应的频道信息
            BLL.channel sbll = new BLL.channel();
            Model.channel from_smodel = sbll.GetModel(from_cmodel.channel_id);
            Model.channel to_smodel = sbll.GetModel(to_cmodel.channel_id);

            //判断两个分类所属频道的模型是否一致
            if (from_smodel.model_id != to_smodel.model_id)
            {
                AppendCache(threadKey, "<div class='error'>两个分类的数据结构不匹配，请确认对应是否正确！<a href='javascript:history.go(-1)'>返回拷贝列表</a></div>");
                return;
            }

            //过滤IdList中的特殊字符
            if (!copy_all)
            {
                //分离ID
                string[] id_arr = id_list.Split(',');
                //过滤数组，拼接IdList
                StringBuilder strIdList = new StringBuilder();
                foreach (string temp in id_arr)
                {
                    int id;
                    if (int.TryParse(temp, out id))
                    {
                        strIdList.Append(id + ",");
                    }
                }
                id_list = strIdList.ToString().Trim(',');
            }

            string condition = "category_id=" + from_category_id;
            if (!copy_all)
            {
                condition = condition + " and id in(" + id_list + ")";
            }

            //找到相应模型，开始对拷
            int copy_num = 0;
            BLL.article abll = new BLL.article();
            List<Model.article> AList = abll.GetModelList(condition);
            foreach (Model.article item in AList)
            {
                Model.article model = item;

                string oldTitle = item.title;
                string oldContent = item.content;

                if (translate)
                {
                    //翻译标题
                    if (StringHelper.IsChinese(oldTitle))
                    {
                        model.title = TranslateHelper.Translate(oldTitle, false);
                        //翻译失败
                        if (string.IsNullOrEmpty(model.title))
                        {
                            model.title = oldTitle;
                        }
                    }
                    //翻译内容
                    if (StringHelper.IsChinese(oldContent))
                    {
                        model.content = TranslateHelper.Translate(oldContent, true);
                        //翻译失败
                        if (string.IsNullOrEmpty(model.content))
                        {
                            model.content = oldContent;
                        }
                    }
                }

                //创建小图副本
                if (make_thumb && File.Exists(PathHelper.MapPath(item.img_url)))
                {
                    string savePath = FileHelper.MakeUploadDire(PageBase.webset.web_path,to_smodel.name, to_category_id);
                    string fileExt = item.img_url.Substring(item.img_url.LastIndexOf('.') + 1);
                    string fullPath = savePath + FileHelper.MakeFileName(fileExt);
                    if (img_width == 0)
                    {
                        File.Copy(PathHelper.MapPath(item.img_url), PathHelper.MapPath(fullPath));
                    }
                    else
                    {
                        ImageThumbnailMake.MakeThumbnail(item.img_url, fullPath, img_width, img_width, "W");
                    }
                    model.img_url = fullPath;
                }

                //过滤HTML标签
                if (clear_tags)
                {
                    model.content = StringHelper.DropHtmlTags(model.content);
                }

                model.category_id = to_category_id;
                int newId = abll.Add(model);
                //拷贝扩展字段
                BLL.attr_field fieldbll = new BLL.attr_field();
                BLL.attr_value valbll = new BLL.attr_value();
                List<Model.attr_value> attrValues = valbll.GetModelList("picture_id=" + item.id);
                if (attrValues.Count > 0)
                {
                    foreach (Model.attr_value avItem in attrValues)
                    {
                        if (fieldbll.Exists(avItem.field_name, from_smodel.id) && fieldbll.Exists(avItem.field_name, to_smodel.id))
                        {
                            Model.attr_field toAttrField = fieldbll.GetModel(avItem.field_name, to_smodel.id);
                            Model.attr_value newAttrVal = new Model.attr_value
                            {
                                picture_id = newId,
                                field_id = toAttrField.id,
                                field_name = toAttrField.name,
                                content = TranslateHelper.Translate(avItem.content, true)
                            };
                            valbll.Add(newAttrVal);
                        }
                    }
                }
                AppendCache(threadKey, string.Format("<font color='green'>√ 文章 {0} 对拷至 {1}</font><br /> ", oldTitle, model.title));
            }
            copy_num = AList.Count;
            AppendCache(threadKey, string.Format(" <div class='success'> 对拷成功,共有{0}条记录被拷贝<a href='javascript:history.go(-1)'>返回拷贝列表</a></div> ", copy_num));
            return;
        }
        #endregion

        #region 批量拷贝分类=========================================
        public int copy_category_num = 0;
        public int copy_article_num = 0;
        private void copy_channel(HttpContext context)
        {
            bool copy_child = InputUtil.Get("copy_child") == "1" ? true : false;
            bool is_translate = InputUtil.Get("is_translate") == "1" ? true : false;
            int from_channel_id = InputUtil.Get("FromChannelId", 0);
            int to_channel_id = InputUtil.Get("ToChannelId", 0);
            string idlist = InputUtil.Form("idlist");
            string[] idArray = idlist.Split(',');

            foreach (string item in idArray)
            {
                int id;
                if (int.TryParse(item, out id))
                {
                    CopyChildList(copy_child, is_translate, 0, 0, id, from_channel_id, to_channel_id);
                }
            }
            AppendCache(threadKey, string.Format(" <div class='success'> 对拷成功,共拷贝{0}个分类，{1}条文章。<a href='javascript:history.go(-1)'>返回拷贝列表</a></div> ", copy_category_num, copy_article_num));
        }


        private void CopyChildList(bool copy_child, bool is_translate, int pid, int to_pid, int from_id, int channel_id, int to_channel_id)
        {
            BLL.category bll = new BLL.category();
            List<Model.category> CateList = bll.GetModelList("parent_id=" + pid + " and id_list like '%," + from_id + ",%'" + " and channel_id=" + channel_id);
            if (CateList.Count == 0)
            {
                return;
            }
            foreach (Model.category model in CateList)
            {
                int oldId = model.id;

                string oldTitle = model.title;
                string oldContent = model.content;

                if (is_translate)
                {
                    //翻译标题
                    if (StringHelper.IsChinese(oldTitle))
                    {
                        model.title = TranslateHelper.Translate(oldTitle, false);
                        //翻译失败
                        if (string.IsNullOrEmpty(model.title))
                        {
                            model.title = oldTitle;
                            AppendCache(threadKey, string.Format("<font color='red'>×分类 {0} 翻译失败</font><br /> ", oldTitle));
                        }
                    }
                }

                model.parent_id = to_pid;
                model.id_list = "";
                model.channel_id = to_channel_id;
                model.is_protected = 0;
                int newId = bll.Add(model);

                model.id = newId;
                if (model.parent_id > 0)
                {
                    model.id_list = bll.GetModel(model.parent_id).id_list + newId + ",";
                }
                else
                {
                    model.id_list = "," + newId + ",";
                }
                bll.Update(model);
                //拷贝分类下数据
                AppendCache(threadKey, string.Format("<font color='green'>√ 分类 {0} 对拷至 {1}</font><br /> ", oldTitle, model.title));
                if (copy_child)
                {
                    CopyChildData(is_translate, channel_id, to_channel_id, oldId, newId);
                }
                copy_category_num++;
                //调用自身迭代
                CopyChildList(copy_child, is_translate, oldId, newId, from_id, channel_id, to_channel_id);
            }
        }

        private void CopyChildData(bool is_translate, int channel_id, int to_channel_id, int category_id, int to_category_id)
        {
            bool clear_tags = InputUtil.Get("clear_tags") == "1" ? true : false;
            bool make_thumb = InputUtil.Get("make_thumb") == "1" ? true : false;
            int img_width = InputUtil.Get("img_width", 0);

            Model.channel channel = new BLL.channel().GetModel(channel_id);
            Model.channel to_channel = new BLL.channel().GetModel(to_channel_id);
            string condition = "category_id=" + category_id;
            BLL.article abll = new BLL.article();
            List<Model.article> ArticleList = abll.GetModelList(condition);
            if (ArticleList != null)
            {
                foreach (Model.article item in ArticleList)
                {
                    Model.article model = item;

                    string oldTitle = item.title;
                    string oldContent = item.content;

                    if (is_translate)
                    {
                        //翻译标题
                        if (StringHelper.IsChinese(oldTitle))
                        {
                            model.title = TranslateHelper.Translate(oldTitle, false);
                            //翻译失败
                            if (string.IsNullOrEmpty(model.title))
                            {
                                model.title = oldTitle;
                                AppendCache(threadKey, string.Format("<font color='red'>× 文章 {0} 标题翻译失败</font><br /> ", oldTitle));
                            }
                        }
                        //翻译内容
                        if (StringHelper.IsChinese(oldContent))
                        {
                            model.content = TranslateHelper.Translate(oldContent, true);
                            //翻译失败
                            if (string.IsNullOrEmpty(model.content))
                            {
                                model.content = oldContent;
                                AppendCache(threadKey, string.Format("<font color='red'>× 文章 {0} 内容翻译失败</font><br /> ", oldTitle));
                            }
                        }
                    }

                    //创建图片副本
                    if (make_thumb && File.Exists(PathHelper.MapPath(item.img_url)))
                    {
                        Upload upload = new Upload();
                        string savePath = FileHelper.MakeUploadDire(PageBase.webset.web_path,to_channel.name, to_category_id);
                        string fileExt = item.img_url.Substring(item.img_url.LastIndexOf('.') + 1);
                        string fullPath = savePath + FileHelper.MakeFileName(fileExt);
                        if (img_width == 0)
                        {
                            File.Copy(PathHelper.MapPath(item.img_url), PathHelper.MapPath(fullPath));
                        }
                        else
                        {
                            ImageThumbnailMake.MakeThumbnail(item.img_url, fullPath, img_width, img_width, "W");
                        }
                        model.img_url = fullPath;
                    }

                    //过滤HTML标签
                    if (clear_tags)
                    {
                        model.content = StringHelper.DropHtmlTags(model.content);
                    }

                    model.category_id = to_category_id;
                    int newId = abll.Add(model);
                    //拷贝扩展字段
                    BLL.attr_field fieldbll = new BLL.attr_field();
                    BLL.attr_value valbll = new BLL.attr_value();
                    List<Model.attr_value> attrValues = valbll.GetModelList("picture_id=" + item.id);
                    if (attrValues.Count > 0)
                    {
                        foreach (Model.attr_value avItem in attrValues)
                        {
                            if (fieldbll.Exists(avItem.field_name, channel_id) && fieldbll.Exists(avItem.field_name, to_channel_id))
                            {
                                Model.attr_field toAttrField = fieldbll.GetModel(avItem.field_name, to_channel_id);
                                Model.attr_value newAttrVal = new Model.attr_value
                                {
                                    picture_id = newId,
                                    field_id = toAttrField.id,
                                    field_name = toAttrField.name,
                                    content = TranslateHelper.Translate(avItem.content, true)
                                };
                                valbll.Add(newAttrVal);
                            }

                        }
                    }
                    copy_article_num++;
                    AppendCache(threadKey, string.Format("<font color='green'>√ 文章 {0} 对拷至 {1}</font><br /> ", oldTitle, model.title));
                }
            }
        }

        private void AppendCache(string cacheKey, string newVal)
        {
            string orignVal = CacheHelper.Get(cacheKey) as string;
            CacheHelper.Insert(cacheKey, orignVal + newVal, 600);
        }

        #endregion

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}